var $ = window.Zepto;
var root = window.player;
var $scope = $(document.body);

var index = 0;
var songList;
var audio = new root.audioControl();



function bindEvent(){

	$scope.on("play:listchange",function(event,index){
		$(".listUI>div").css({"background-color":"black"});
		var songindex = controlManger.getIndex(0);
		$("#"+songindex+"").css({"background-color":"#49f"});
	})

	$scope.on("play:change",function(event,index){
		audio.getAudio(songList[index].audio);
		if(audio.status == "play"){
			audio.play();
			root.process.start();
		}

		root.process.renderAllTime(songList[index].duration);//切歌重新渲染歌曲总时间
		
		root.render(songList[index]);//切歌重新渲染页面
		root.process.updata(0);//切歌重新渲染时间和进度条
	})

	$scope.on("click",".like-btn",function(){
		if(songList[index].islike){
			songList[index].islike = false;
			$.ajax({
			   type: "POST",
			   url: "../mock/data.json",
			   data: "name=John&location=Boston",
			   success: function(msg){
			     alert( "Data Saved: " + msg );
			   }
			});
		}else{
			songList[index].islike = true;
		}
		root.renderIsLike(songList[index].islike);
		
	})

	$scope.on("click",".prev-btn",function(){
		
		var index = controlManger.prev();
		$scope.trigger("play:change",index); 
		$scope.trigger("play:listchange"); 
		
	})
	$scope.on("click",".next-btn",function(){
		
		var index = controlManger.next();
		$scope.trigger("play:change",index); 
		$scope.trigger("play:listchange"); 
	})
	$scope.on("click",".play-btn",function(){
		if(audio.status == "play"){
			audio.pause();
			root.process.stop();
			$(this).removeClass("pause");
		}else{
			audio.play();
			root.process.start();
			$(this).addClass("pause");
		}
		$scope.trigger("play:listchange"); 

		
	})
	$scope.on("click",".list-btn",function(){
		$(".listUI").toggle();
		
	})
}

function bindTouch(){
	var $slider = $scope.find(".slider-pointer");
	var offset = $scope.find(".pro-wrapper").offset();
	var left = offset.left;
	var width = offset.width;
	$slider.on("touchstart",function(){
		root.process.stop();
	}).on("touchmove",function(e){
		var x = e.changedTouches[0].clientX;
		var per = (x - left) / width;
		if(per < 0){
			per = 0;
		}else if(per > 1){
			per = 1;
		}
		root.process.updata(per);
	}).on("touchend",function(e){
		var x = e.changedTouches[0].clientX;
		var per = (x - left) / width;
		if(per < 0){
			per = 0;
		}else if(per > 1){
			per = 1;
		}
		var curDuration = songList[controlManger.index].duration
		var curTime = per * curDuration;
		audio.playTo(curTime);
		root.process.start(per);
		$scope.find(".play-btn").addClass("pause");
	})
}

function getData(url){
	$.ajax({
		type: "GET",
		url: url,
		success: function(data){
			root.render(data[0]);
			songList = data;
			bindEvent();
			controlManger = new root.controlManger(data.length);
			console.log(data);
			$scope.trigger("play:change",0); 
			bindTouch();
			root.addsongtolist(data);
		},
		error: function(){
			console.log("error");
		}
	})
}
getData("../mock/data.json");